<?php
namespace app\admin\controller;

use app\common\model\AppointmentUpstart as AppointmentUpstartModel;
use app\common\model\HelpGetUpstart as HelpGetUpstartModel;

use app\common\component\help_to_upstart\HelpToUpstartService;
use app\common\component\help_get_upstart\HelpGetUpstartService;

class HelpGetUpstart extends ControllerBase {
	public function _initialize() {
		$this -> checkLogin();

		$this -> checkAuthorization();
	}

	public function index() {
		$resultHelpGetUpstart = HelpGetUpstartModel::alias('h_g_u')
			-> join('league_user u', 'h_g_u.user_id = u.user_id')
			-> field(
				'h_g_u.help_get_upstart_id, h_g_u.order_id, h_g_u.price, h_g_u.create_time, h_g_u.status, ' .
				'u.username, u.realname, u.phone, u.bank_code'
			)
			-> order('h_g_u.status ASC, h_g_u.sort ASC')
			-> paginate(10);
		$this -> view -> assign('helpGetUpstarts', $resultHelpGetUpstart);

		$this -> view -> assign('totalAppointmentUpstart', AppointmentUpstartModel::where('status', 0) -> count());

		return $this -> view -> fetch();
	}

	public function match() {
		$helpGetUpstartId = $this -> request -> get('help_get_upstart_id', 0, 'int');

		$getHelpGetUpstart = HelpGetUpstartModel::get(['help_get_upstart_id' => $helpGetUpstartId]);
		if(!$getHelpGetUpstart || $getHelpGetUpstart -> getData('status') != 0) {
			echo '<meta charset="utf-8"><script>alert("提现订单不存在或已经匹配完成!");window.location.href="/shuashuale/helpTo/upstart";</script>';exit;
		}
		$this -> view -> assign('helpGetUpstart', $getHelpGetUpstart);

		$findAppointmentUpstart = AppointmentUpstartModel::alias('a_u')
			-> join('league_user u', 'a_u.user_id = u.user_id')
			-> field(
				'a_u.help_appointment_upstart_id, a_u.user_id, a_u.appointment_price, a_u.remaining_price, a_u.create_time, a_u.begin_time, a_u.to_num, a_u.status, ' .
				'u.username, u.realname, u.phone, u.bank_code'
			)
			-> order('a_u.status ASC, a_u.begin_time ASC')
			-> where('a_u.status = 0 AND a_u.remaining_price = ' . $getHelpGetUpstart -> price . ' AND a_u.user_id <> ' . $getHelpGetUpstart -> user_id)
			-> find();
		$this -> view -> assign('appointmentUpstart', $findAppointmentUpstart);

		return $this -> view -> fetch();
	}

	public function handleMatch() {
		$post = $this -> request -> post();
		if(!isset($post['help_appointment_upstart_id'])) {
			echo '<meta charset="utf-8"><script>alert("无选择匹配订单!");window.location.href="/shuashuale/helpTo/upstart";</script>';exit;
		}

		$getHelpGetUpstart = HelpGetUpstartModel::get(['help_get_upstart_id' => $post['help_get_upstart_id']]);
		if(!$getHelpGetUpstart || $getHelpGetUpstart -> getData('status') != 0) {
			echo '<meta charset="utf-8"><script>alert("提现订单不存在或已经匹配完成!");window.location.href="/shuashuale/helpTo/upstart";</script>';exit;
		}
		$currentTime = time();

		$getAppointmentUpstart = AppointmentUpstartModel::get(['help_appointment_upstart_id' => $post['help_appointment_upstart_id']]);
		\think\Db::startTrans();
		try {
			$getAppointmentUpstart -> remaining_price = 0;
			$getAppointmentUpstart -> begin_time = $currentTime;
			$getAppointmentUpstart -> to_num += 1;
			$getAppointmentUpstart -> status = 1;
			if(!$getAppointmentUpstart -> save()) {
				throw new \Exception('预约,匹配失败');
			}

			$resultHelpToUpstart = (new HelpToUpstartService()) -> create([
				'help_get_upstart_id' => $getHelpGetUpstart -> help_get_upstart_id,
				'user_id' => $getAppointmentUpstart -> user_id,
				'price' => $getHelpGetUpstart -> price,
				'create_time' => $currentTime,
				'begin_time' => $currentTime,
				'over_time' => $currentTime + getParam('HELP_TO_RICH_OVERTIME') * 60 * 60,
				'status' => 1
			]);
			if($resultHelpToUpstart['code'] != 0) {
				throw new \Exception('打款,匹配失败');
			}

			$getHelpGetUpstart -> status = 1;
			$getHelpGetUpstart -> begin_time = $currentTime;
			$getHelpGetUpstart -> help_to_upstart_id = $resultHelpToUpstart['data']['help_to_upstart'] -> help_to_upstart_id;
			if(!$getHelpGetUpstart -> save()) {
				throw new \Exception('提现,个别订单匹配失败');
			}

			\think\Db::commit();
		} catch(\Exception $e) {
			\think\Db::rollback();

			echo '<meta charset="utf-8"><script>alert("' . $e -> getMessage() . '!");window.location.href="/shuashuale/helpTo/upstart/match?help_get_upstart_id=' . $post['help_get_upstart_id'] . '";</script>';exit;
		}

		echo '<meta charset="utf-8"><script>alert("订单匹配成功!");window.location.href="/shuashuale/helpTo/upstart";</script>';exit;
	}

	public function separate() {
		$helpGetUpstartId = $this -> request -> get('help_get_upstart_id', 0, 'int');

		$getHelpGetUpstart = HelpGetUpstartModel::get(['help_get_upstart_id' => $helpGetUpstartId]);
		if(!$getHelpGetUpstart || $getHelpGetUpstart -> price <= 0 || $getHelpGetUpstart -> getData('status') != 0) {
			if($getHelpGetUpstart -> price <= 0) {
				$getHelpGetUpstart -> price = 0;
				$getHelpGetUpstart -> status = 4;
				$getHelpGetUpstart -> save();
			}
			echo '<meta charset="utf-8"><script>alert("提现订单不存在或已经匹配完成!");window.location.href="/shuashuale/helpGet/upstart";</script>';exit;
		}
		$this -> view -> assign('helpGetUpstart', $getHelpGetUpstart);

		return $this -> view -> fetch();
	}

	public function handleSeparate() {
		$post = $this -> request -> post();
		if($post['price'] <= 0) {
			echo '<meta charset="utf-8"><script>alert("拆单金额不能小于0!");window.location.href="/shuashuale/helpGet/upstart/separate?help_get_upstart_id=' . $post['help_get_upstart_id'] .'";</script>';exit;
		}

		$getHelpGetUpstart = HelpGetUpstartModel::get(['help_get_upstart_id' => $post['help_get_upstart_id']]);
		if(!$getHelpGetUpstart || $getHelpGetUpstart -> price <= 0 || $getHelpGetUpstart -> getData('status') != 0) {
			if($getHelpGetUpstart -> price <= 0) {
				$getHelpGetUpstart -> price = 0;
				$getHelpGetUpstart -> status = 4;
				$getHelpGetUpstart -> save();
			}
			echo '<meta charset="utf-8"><script>alert("提现订单不存在或已经匹配完成!");window.location.href="/shuashuale/helpGet/upstart";</script>';exit;
		}

		if($post['price'] > $getHelpGetUpstart -> price) {
			echo '<meta charset="utf-8"><script>alert("拆单金额不能大于当前订单!");window.location.href="/shuashuale/helpGet/upstart/separate?help_get_upstart_id=' . $post['help_get_upstart_id'] .'";</script>';exit;
		}

		if(($getHelpGetUpstart -> price - $post['price']) == 0) {
			echo '<meta charset="utf-8"><script>alert("被拆订单不能等于0!");window.location.href="/shuashuale/helpGet/upstart/separate?help_get_upstart_id=' . $post['help_get_upstart_id'] .'";</script>';exit;
		}

		$getHelpGetUpstart -> price -= $post['price'];
		$currentTime = time();

		\think\Db::startTrans();
		try {
			if(!$getHelpGetUpstart -> save()) {
				throw new \Exception('拆单失败, $getHelpGetUpstart save');
			}

			$createHelpGetUpstart = (new HelpGetUpstartService()) -> create([
				'help_to_upstart_id' => 0,
				'user_id' => $getHelpGetUpstart -> user_id,
				'price' => $post['price'],
				'create_time' => $currentTime, 
				'begin_time' => $currentTime,
				'status' => 0,
				'sort' => 0,
			]);
	    	if($createHelpGetUpstart['code'] !== 0) {
	    		throw new \Exception($createHelpGetUpstart['message']);
	    	}

			\think\Db::commit();
		} catch(\Exception $e) {
			\think\Db::rollback();

			echo '<meta charset="utf-8"><script>alert("' . $e -> getMessage() . '!");window.location.href="/shuashuale/helpGet/upstart/separate?help_get_upstart_id=' . $post['help_get_upstart_id'] .';</script>';exit;
		}

		echo '<meta charset="utf-8"><script>alert("拆单成功!");window.location.href="/shuashuale/helpGet/upstart";</script>';exit;
	}
}
?>